$(function () {

    var activeLink = null;

    $(document.body).on('touchstart', 'a', function () {
        activeLink = this;
        $(activeLink).addClass('g-active');
    });

    $(document.body).on('touchend', 'a', function () {
        $(activeLink).removeClass('g-active');
    });

    // $(document.body).append('<div id="page-loading" style="display: none;">' +
    //     '<img src="' + _home + '/img/page-loading.gif"/></div>');
    // document.body.onbeforeunload = function () {
         //$(document.body).append('<div class=''></div>');
        // setTimeout(function () {
        // console.log('leaving..' + new Date());
            // $('#page-loading').show();
        // }, 100);
    // };

    //
    var app = {};

    app.alert = function (msg, callback) {
        var html = '<div class="weui_dialog_alert" id="dlgAlert" style="display: none;">' +
            '<div class="weui_mask"></div>' +
            '<div class="weui_dialog">' +
            '<div class="weui_dialog_hd"><strong class="weui_dialog_title">提示</strong></div>' +
            '<div class="weui_dialog_bd">弹窗内容，告知当前页面信息等</div>' +
            '<div class="weui_dialog_ft">' +
            '<a href="javascript:;" class="weui_btn_dialog primary">确定</a>' +
            '</div>' +
            '</div>' +
            '</div>';
        var $dlgAlert = $('#dlgAlert');
        if(!$dlgAlert.length) {
            $(document.body).append(html);
            $dlgAlert = $('#dlgAlert');
        }
        $dlgAlert.find('.weui_dialog_bd').html(msg);
        $dlgAlert.show().on('click', '.weui_btn_dialog', function () {
            $dlgAlert.off('click').hide();
            callback && callback();
        });
    };

    app.confirm = function (msg, callback) {
        var html = '<div class="weui_dialog_confirm" id="dlgConfirm" style="display:none;">' +
            '<div class="weui_mask"></div>' +
            '<div class="weui_dialog">' +
            '<div class="weui_dialog_hd"><strong class="weui_dialog_title">提示</strong></div>' +
            '<div class="weui_dialog_bd">content</div>' +
            '<div class="weui_dialog_ft">' +
            '<a href="javascript:;" class="weui_btn_dialog default">取消</a>' +
            '<a href="javascript:;" class="weui_btn_dialog primary">确定</a>' +
            '</div>' +
            '</div>' +
            '</div>';
        var $dlg = $('#dlgConfirm');
        if(!$dlg.length) {
            $(document.body).append(html);
            $dlg = $('#dlgConfirm');
        }
        $dlg.find('.weui_dialog_bd').text(msg);
        $dlg.show().on('click', '.weui_btn_dialog', function () {
            if($(this).hasClass('primary')) {
                callback && callback();
            }
            $dlg.off('click').hide();
        });
    };

    app.prompt = function (msg, callback) {
        var html = '<div class="weui_dialog_confirm prompt" id="dlgPrompt" style="display:none;">' +
            '<div class="weui_mask"></div>' +
            '<div class="weui_dialog">' +
            '<div class="weui_dialog_hd"><strong class="weui_dialog_title">提示</strong></div>' +
            '<div class="weui_dialog_bd">content</div>' +
            '<div class="weui_dialog_ft">' +
            '<a href="javascript:;" class="weui_btn_dialog default">取消</a>' +
            '<a href="javascript:;" class="weui_btn_dialog primary">确定</a>' +
            '</div>' +
            '</div>' +
            '</div>';
        var $dlg = $('#dlgPrompt');
        if(!$dlg.length) {
            $(document.body).append(html);
            $dlg = $('#dlgPrompt');
        }
        var bodyHtml = '<div>' + msg + '</div>' +
            '<div class="input"><input type="text"/></div>';
        $dlg.find('.weui_dialog_bd').html(bodyHtml);
        var $input = $dlg.find('input');
        var winHeight = $(window).height();

        $input.one('focus.dlg-prompt', function () {
            setTimeout(function () {
                var newWinHeight = $(window).height();
                if(newWinHeight == winHeight && winHeight > 479) {
                    $input.blur();
                    $dlg.addClass('shrink');

                    var $weuiDialog = $dlg.find('.weui_dialog');
                    $weuiDialog.one('transitionend webkitTransitionEnd', function () {
                        $input.focus();
                    });
                }
            }, 501)
        });
        $dlg.show().on('click', '.weui_btn_dialog', function () {
            if($(this).hasClass('primary')) {
                callback && callback($input.val());
            }
            $dlg.remove();
        });
        setTimeout(function () {
            $input.focus();
        }, 100);
    };

    //
    var loadingCount = 0;
    var nextLoadingCookie = 1;
    var loadingCookies = {};
    var forceHideLoaderTimer;

    function forceHideLoader() {
        loadingCount = 0;
        loadingCookies = {};
        $('#ui_loader').hide();
    }

    function buildUILoader() {
        var html = '<div id="ui_loader" class="weui_loading_toast" style="display:none;">' +
            '<div class="weui_mask_transparent"></div>' +
            '<div class="weui_toast">' +
            '<div class="weui_loading">' +
            '<div class="weui_loading_leaf weui_loading_leaf_0"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_1"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_2"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_3"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_4"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_5"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_6"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_7"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_8"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_9"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_10"></div>' +
            '<div class="weui_loading_leaf weui_loading_leaf_11"></div>' +
            '</div>' +
            // <p class="weui_toast_content">数据加载中</p>
            '</div>' +
            '</div>';
        $(document.body).append(html);
        return $('#ui_loader');
    }

    app.showLoading = function () {
        if(loadingCount == 0) {
            var $uiLoader = $('#ui_loader');
            if(!$uiLoader.length) {
                $uiLoader = buildUILoader();
            }
            $uiLoader.show();
        }
        ++loadingCount;
        var cookie = nextLoadingCookie++;
        loadingCookies[cookie] = true;
        clearTimeout(forceHideLoaderTimer);
        forceHideLoaderTimer = setTimeout(forceHideLoader, 1000 * 20);
        //console.log('@ show loading...(' + cookie + ')');
        return cookie;
    };

    app.hideLoading = function (cookie) {
        //console.log('@ hide loading...(' + cookie + ')');
        if(cookie !== undefined && !(cookie in loadingCookies)) {
            return;
        }
        if(loadingCount == 0) {
            return;
        }
        --loadingCount;
        if(loadingCount == 0) {
            clearTimeout(forceHideLoaderTimer);
            $('#ui_loader').hide();
            loadingCookies = {};
        }
    };

    app.showSuccess = function (msg, timeout) {
        var html = '<div id="_toast" style="display: none;">' +
            '<div class="weui_mask_transparent"></div>' +
            '<div class="weui_toast">' +
            '<i class="weui_icon_toast"></i>' +
            '<p class="weui_toast_content">已完成</p>' +
            '</div>' +
            '</div>';
        var $toast = $('#_toast');
        if(!$toast.length) {
            $(document.body).append(html);
            $toast = $('#_toast');
        }
        $toast.find('.weui_toast_content').text(msg || '已完成');
        $toast.show();
        setTimeout(function () {
            $toast.hide();
        }, timeout || 2000);
    };

    app.gotoUrl = function (url) {
        setTimeout(function () {
            $('#page-loading').show();
        }, 160);
        location = url;
    };


    ////

    app.fixWxKeyboard = function (input, relButton) {
        var $input = $(input);
        var shrinkOnFocus;
        var winHeight = $(window).height();
        function shrinkBody() {
            $(document.body).addClass('shrink');
            setTimeout(function () {
                var main = $('main')[0];
                main.scrollTop = $(window).height() * 0.5;
            }, 10);
        }
        $input.on('focus', function () {
            if(shrinkOnFocus) {
                shrinkBody();
            }
            (shrinkOnFocus === undefined) && setTimeout(function () {
                if(winHeight == $(window).height()) {
                    shrinkOnFocus = true;
                    shrinkBody();
                }
            }, 600);
        });
        var blurTimer;
        $input.on('blur', function () {
            blurTimer = setTimeout(function () {
                $(document.body).removeClass('shrink');
            }, 310);
        });
        //
        $(relButton).on('focus', function () {
            clearTimeout(blurTimer);
            $input.focus();
        });
    };

    window.app = app;
});

(function () {
    //
    var backService = {
        //loading: 0
        requests: [],
        ajaxTimeout: 24000
    };

    backService.baseUrl = _home;

    backService.failureHandler = function(json) {
        if(json.status === 'abort') {
            return;
        }
        else if(json.status === 'timeout') {
            app.alert('请求超时');
            return;
        }
        var msg = json.msg || json.type;
        if(msg.length > 256) {
            alert(msg);
        }
        else {
            app.alert(msg);
        }
    };

    backService.get = function (url, data, callback, failure) {
        backService.ajax('GET', url, data, callback, failure);
    };

    backService.post = function (url, data, callback, failure) {
        backService.ajax('POST', url, data, callback, failure);
    };

    backService.ajax = function (method, url, data, callback, failure) {
        var ajaxArguments = arguments;

        if(typeof(data) === 'function') {
            failure = callback;
            callback = data;
        }
        //if (callback === undefined) {
        //    callback = data;
        //}
        if(failure === undefined) {
            failure = backService.failureHandler
        }
        if (url.indexOf('http:') == -1) {
            url = backService.baseUrl + url;
        }
        var completed = false;
        var loadingDelay = 500;
        if (backService.immediateLoading) {
            loadingDelay = 0;
            backService.immediateLoading = false;
        }
        var loadingCookie;
        if (backService.noLoading) {
            backService.noLoading = false;
        }
        else {
            if(backService.loadingDelay) {
                loadingDelay = backService.loadingDelay;
                delete backService.loadingDelay;
            }
            setTimeout(function () {
                if (completed) {
                    return;
                }
                loadingCookie = app.showLoading();
            }, loadingDelay);
        }
        //++backService.loading;
        var headers = {};
        // if(session.user && backService.token) {
        //     var ownerToken = backService.token + Number(session.user.id).toString(16);
        //     //headers['x-owner-token'] = ownerToken;
        //     headers['Accept'] = 'json-' + ownerToken;
        // }

        var request = $.ajax(url, {
            method: method,
            data: data,
            dataType: 'json',
            traditional: true,
            timeout: backService.ajaxTimeout,
            headers: headers,
            xhrFields: {
                withCredentials: true
            },
            success: function (json) {
                completed = true;
                if (loadingCookie) {
                    app.hideLoading(loadingCookie);
                }
                if(json.ok) {
                    try {
                        callback && callback(json);
                    }
                    catch(e) {
                        if(inBrowser) {
                            throw e;
                        }
                        var loc = '[Ajax Callback Error]';
                        if(e.fileName) {
                            loc += '[' + e.fileName;
                            if(e.lineNumber) {
                                loc += ':' + e.lineNumber;
                            }
                            loc += ']';
                        }
                        console.log(loc + e.message);
                        if(app.debug && e.stack) {
                            console.log('>> ' + e.stack);
                        }
                    }
                }
                else {
                    if(json.error && json.msg == 'ERR::BAD_TOKEN' &&
                        !backService.ajax.inRequestTokenCallback) {

                        backService.requestToken(function() {
                            backService.ajax.inRequestTokenCallback = true;
                            backService.ajax.apply(this, ajaxArguments);
                        });
                    }
                    else {
                        failure(json);
                    }
                }
            },
            error: function (xhr, status, err) {
                failure({
                    ok: false,
                    status: status,
                    msg: status + ': ' + err
                });
            },
            complete: function (xhr, statusText) {
                backService.ajax.inRequestTokenCallback = false;
                //--backService.loading;
                for(var n = 0; n < backService.requests.length; n++) {
                    if(backService.requests[n] === request) {
                        backService.requests.splice(n, 1);
                        break;
                    }
                }
                if(!completed) {
                    completed = true;
                    if (loadingCookie) {
                        app.hideLoading(loadingCookie);
                    }
                }
            }
        });
        backService.requests.push(request);
    };

    window.backService = backService;
})();
